
#import "BDMapManager.h"
#import "BDMapView.h"
#import <BaiduMapAPI_Base/BMKBaseComponent.h>//引入base相关所有的头文件
#import <BaiduMapAPI_Map/BMKMapComponent.h>//引入地图功能所有的头文件
#import <BaiduMapAPI_Location/BMKLocationComponent.h>//引入定位功能所有的头文件
#import <BaiduMapAPI_Search/BMKSearchComponent.h>//引入检索功能所有的头文件
#import <React/RCTBridge.h>
#import <React/RCTUIManager.h>
#import <React/UIView+React.h>

@interface BDMapManager()<BMKMapViewDelegate,BMKGeoCodeSearchDelegate>
{
}
@property (strong, nonatomic) BDMapView *mapView;
@end

@implementation BDMapManager

BMKProjectInfoAnnotationView *lastSelectedProjectAnnotationView;
BDMapAnnotation *currentProjectAnnotationInfo;

BMKGeoCodeSearch *_geoSearch;
bool needSendonGetReverseGeoCodeResulteEvent;

- (dispatch_queue_t)methodQueue
{
    return dispatch_get_main_queue();
}
RCT_EXPORT_MODULE()



-(instancetype)init{
    self = [super init];
    if (self) {
        currentProjectAnnotationInfo = nil;
        lastSelectedProjectAnnotationView = nil;
        _geoSearch = [[BMKGeoCodeSearch alloc]init] ;
        _geoSearch.delegate = self;
        needSendonGetReverseGeoCodeResulteEvent = YES;
    }
    return  self;
}

- (UIView *)view {
    
    _mapView = [BDMapView new];
    _mapView.delegate = self;
    // 设置地图类型
    [_mapView setMapType:BMKMapTypeStandard];
    // 普通定位模式
    _mapView.userTrackingMode = BMKUserTrackingModeNone;
    
    return _mapView;
}


RCT_EXPORT_VIEW_PROPERTY(mapAnnotations, NSArray<BDMapAnnotation *>)
RCT_EXPORT_VIEW_PROPERTY(mapUpdateStatus, MapStatusInfo *)
RCT_EXPORT_VIEW_PROPERTY(onChange, RCTBubblingEventBlock)

//实现相关delegate


- (BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id <BMKAnnotation>)annotation
{
    
    if ([annotation isKindOfClass:[BMKPointAnnotation class]]) {
        BDMapAnnotation *anno = (BDMapAnnotation *)annotation;
        BMKAnnotationView *newAnnotationView;
        if(anno.areaType == 1 || anno.areaType == 2){
            newAnnotationView = [[BMKCircleAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"annotation"];
            ((BMKCircleAnnotationView *)newAnnotationView).delegate = self;
            ((BMKCircleAnnotationView *)newAnnotationView).lblCount.text =[NSString stringWithFormat:@"%li",anno.projectCount] ;
            
            ((BMKCircleAnnotationView *)newAnnotationView).lblName.text =  anno.areaName;
            
        }
        else{
            
            
            newAnnotationView = [[BMKProjectInfoAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"annotation"];
            ((BMKProjectInfoAnnotationView *)newAnnotationView).delegate = self;
            ((BMKProjectInfoAnnotationView *)newAnnotationView).bgIcon.image = [UIImage imageNamed:(anno.projectLevel != 1 ? @"icon_project_normal":@"icon_project_important")] ;
            [((BMKProjectInfoAnnotationView *)newAnnotationView) displayProjectName:anno.projectName];
        }
        
        
        
        return newAnnotationView;
    }
    return nil;
}

-(void)mapView:(BMKMapView *)mapView regionWillChangeAnimated:(BOOL)animated
{
    if(lastSelectedProjectAnnotationView)
    {
        BDMapAnnotation *lastData =   lastSelectedProjectAnnotationView.annotation;
        lastSelectedProjectAnnotationView.bgIcon.image = [UIImage imageNamed:(lastData.projectLevel != 1 ? @"icon_project_normal":@"icon_project_important")] ;
        lastSelectedProjectAnnotationView = nil;
    }
    NSDictionary<NSString *, id> *info = @{
                                           @"zoomLevel":  [NSNumber numberWithFloat:_mapView.zoomLevel]
                                           };
    [self sendEvent:_mapView withTypeName:@"onMapStatusChangeStart" params:info];
    
}

-(void)mapView:(BMKMapView *)mapView regionDidChangeAnimated:(BOOL)animated
{
    //    if(currentProjectAnnotationInfo != nil)
    //    {
    //        NSDictionary<NSString *, id> *info = @{
    //                                               @"zoomLevel":  [NSNumber numberWithFloat:_mapView.zoomLevel],
    //                                               @"projectCode": (currentProjectAnnotationInfo.projectCode ? currentProjectAnnotationInfo.projectCode:@"")
    //                                               };
    //        [self sendEvent:_mapView withTypeName:@"onMapStatusChangeFinish" params:info];
    //    }
    //
    if(needSendonGetReverseGeoCodeResulteEvent)
    {
        [self reverseGeoSearch:CLLocationCoordinate2DMake(_mapView.centerCoordinate.latitude, _mapView.centerCoordinate.longitude)];
    }
    else
    {
        needSendonGetReverseGeoCodeResulteEvent = YES;
    }
    
}
- (void)reverseGeoSearch:(CLLocationCoordinate2D) pt{
    BMKReverseGeoCodeOption *reverseGeocodeSearchOption = [[BMKReverseGeoCodeOption alloc]init];
    reverseGeocodeSearchOption.reverseGeoPoint = pt;
    BOOL flag = [_geoSearch reverseGeoCode:reverseGeocodeSearchOption];
    if(flag)
    {
        NSLog(@"反geo检索发送成功");
    }
    else
    {
        NSLog(@"反geo检索发送失败");
    }
}

-(void)onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error{
    if (error == BMK_SEARCH_NO_ERROR && result && result.addressDetail) {
        NSDictionary<NSString *, id> *info =  @{
                                                @"zoomLevel": [NSNumber numberWithDouble:_mapView.zoomLevel],
                                                @"target":@{@"latitude":[NSNumber numberWithDouble:result.location.latitude],@"longitude":[NSNumber numberWithDouble:result.location.longitude]},
                                                @"address":@{@"province":result.addressDetail.province
                                                             ,@"city":result.addressDetail.city
                                                             ,@"district":result.addressDetail.district
                                                             },
                                                };
        
        [self sendEvent:_mapView withTypeName:@"onGetReverseGeoCodeResult" params:info];
        
    }
}

-(void)BMKCircleAnnotationView:(BMKCircleAnnotationView *)sel clickViewWithData:(BDMapAnnotation *)data
{
    BDMapAnnotation *selectedAnnotation = data;
    if (selectedAnnotation) {
        needSendonGetReverseGeoCodeResulteEvent = NO;
        [_mapView setCenterCoordinate:data.coordinate animated:NO];
        NSDictionary<NSString *, id> *annotationInfo =  @{
                                                          @"areaCode": (data.areaCode ? data.areaCode:@""),
                                                          @"areaName": (data.areaName ? data.areaName:@""),
                                                          @"areaType":  [NSNumber numberWithInteger:data.areaType],
                                                          @"locationY": [NSNumber numberWithFloat:data.coordinate.latitude],
                                                          @"locationX": [NSNumber numberWithFloat:data.coordinate.longitude],
                                                          @"projectCount": [NSNumber numberWithInteger:data.projectCount],
                                                          @"projectCode": (data.projectCode ? data.projectCode:@""),
                                                          @"projectName":  (data.projectName ? data.projectName:@""),
                                                          @"projectLevel": [NSNumber numberWithInteger:data.projectLevel]
                                                          };
        [self sendEvent:_mapView withTypeName:@"onDataSelect" params:annotationInfo];
        
    }
}

-(void)BMKProjectInfoAnnotationView:(BMKProjectInfoAnnotationView *)sel clickViewWithData:(BDMapAnnotation *)data
{
    currentProjectAnnotationInfo = data;
    needSendonGetReverseGeoCodeResulteEvent = NO;
    [_mapView setCenterCoordinate:data.coordinate animated:NO];
    if([lastSelectedProjectAnnotationView isEqual:sel])
    {
        BDMapAnnotation *lastData =   lastSelectedProjectAnnotationView.annotation;
        lastSelectedProjectAnnotationView.bgIcon.image = [UIImage imageNamed:(lastData.projectLevel != 1 ? @"icon_project_normal":@"icon_project_important")] ;
        NSDictionary<NSString *, id> *info = @{
                                               @"zoomLevel":  [NSNumber numberWithFloat:_mapView.zoomLevel],
                                               @"projectCode": (currentProjectAnnotationInfo.projectCode ? currentProjectAnnotationInfo.projectCode:@"")
                                               };
        [self sendEvent:_mapView withTypeName:@"onProjectSelect" params:info];
        lastSelectedProjectAnnotationView = nil;
        return;
    }
    
    if(lastSelectedProjectAnnotationView)
    {
        BDMapAnnotation *lastData =   lastSelectedProjectAnnotationView.annotation;
        lastSelectedProjectAnnotationView.bgIcon.image = [UIImage imageNamed:(lastData.projectLevel != 1 ? @"icon_project_normal":@"icon_project_important")]  ;
    }
    sel.bgIcon.image = [UIImage imageNamed:(data.projectLevel != 1 ? @"icon_project_normal_selected":@"icon_project_important_selected")]  ;
    
    
    lastSelectedProjectAnnotationView = sel;
    
    NSDictionary<NSString *, id> *info = @{
                                           @"zoomLevel":  [NSNumber numberWithFloat:_mapView.zoomLevel],
                                           @"projectCode": (currentProjectAnnotationInfo.projectCode ? currentProjectAnnotationInfo.projectCode:@"")
                                           };
    [self sendEvent:_mapView withTypeName:@"onProjectSelect" params:info];
    
}

-(void)mapView:(BMKMapView *)mapView onClickedMapBlank:(CLLocationCoordinate2D)coordinate
{
    
    if(lastSelectedProjectAnnotationView)
    {
        BDMapAnnotation *lastData =   lastSelectedProjectAnnotationView.annotation;
        lastSelectedProjectAnnotationView.bgIcon.image = [UIImage imageNamed:(lastData.projectLevel != 1 ? @"icon_project_normal":@"icon_project_important")];
        
        [self sendEvent:_mapView withTypeName:@"onMapClick" params:@{
                                                                     @"latitude": [NSNumber numberWithDouble:coordinate.latitude],
                                                                     @"longitude": [NSNumber numberWithDouble:coordinate.longitude]
                                                                     }];
        lastSelectedProjectAnnotationView = nil;
    }
}
-(void)sendEvent:(BDMapView *) mapView withTypeName:(NSString *)typeName params:(NSDictionary *) params {
    if (!mapView.onChange) {
        return;
    }
    mapView.onChange(@{
                       @"type": typeName,@"params":params
                       });
    
}
@end

